use agent::generic::{create_agent, ProviderConfig};
use common::compose::{CallBox, Composer, make_empty_ctx};
use log::warn;

/// 创建一个检测语言的 CallBox
///
/// 该 CallBox 接收一个文本片段，返回ISO 639-1语言代码
///
/// # 参数
///
/// * `config` - 提供商配置
///
/// # 返回值
///
/// 返回一个 CallBox，该 CallBox 接收一个字符串，返回语言代码
pub fn make_check_lang_callbox(config: ProviderConfig) -> CallBox<'static, String, String> {
    // 系统提示词
    let system_prompt = r#"
You are a language detection expert. Your task is to identify the language of the provided text and return only the ISO 639-1 language code.

For example:
- English text should return "en"
- Chinese text should return "zh"
- Spanish text should return "es"
- French text should return "fr"
- German text should return "de"
- Japanese text should return "ja"
- Russian text should return "ru"
- Italian text should return "it"
- Portuguese text should return "pt"
- Korean text should return "ko"
- Arabic text should return "ar"
- Hindi text should return "hi"

Only return the language code without any additional text, explanation, or formatting.
"#;

    // 创建代理
    let agent = create_agent(config, "", system_prompt);

    // 包装代理，确保只返回语言代码
    Composer::from_fn(move |text: String| {
        let agent = agent.clone();

        async move {
            // 只取文本的前 1000 个字符进行语言检测
            let sample = if text.len() > 1000 {
                text.chars().take(1000).collect::<String>()
            } else {
                text
            };

            let result = agent.run(sample, make_empty_ctx()).await?;

            // 清理结果，确保只返回语言代码
            let lang_code = result.trim().to_lowercase();

            // 验证语言代码格式
            if lang_code.len() != 2 {
                warn!("语言检测返回了非标准的语言代码: {}", lang_code);
                return Ok("en".to_string()); // 默认返回英语
            }

            Ok(lang_code)
        }
    })
}
